#include "File.h"

// TODO: remove after debugging
#include <OgreLogManager.h>
#define LOG(M) Ogre::LogManager::getSingleton().logMessage(M)
///////////////////////////////

namespace MHX
{

	// Read in an MHX file
	bool File::parse(std::istream &in)
	{
		// First tokenize by line
		TokenLines lines;
		{
			std::string line;

			while(std::getline(in, line))
			{
				size_t lineStart = line.find_first_not_of(" \t");

				if(lineStart == std::string::npos)
					continue;

				lines.push_back(tokenize(line.substr(lineStart), " \t"));
			}
		}

		// Parse file line-by-line
		for(LineIterator line = lines.begin(); line != lines.end(); line++)
		{
			if(line->size() > 1 && line->at(0).compare("Mesh") == 0)
			{
				std::string meshName = line->at(1);

				Mesh &m = MHX::Mesh();

				if(m.parse(line))
					meshes[meshName] = m;
			}

			if(line->size() > 0 && line->at(0).compare("Armature") == 0)
			{
			}
		}

		return true;
	}

	// String tokenization from Gamedev forum users Oluseyi and Drew_Benton:
	// http://www.gamedev.net/community/forums/topic.asp?topic_id=310530
	TokenLine File::tokenize(const Token &str, const std::string &delim)
	{
		TokenLine tokens;

		size_t p0 = 0, p1 = std::string::npos;
		while(p0 != std::string::npos)
		{
			p1 = str.find_first_of(delim, p0);
			if(p1 != p0)
			{
				Token token = str.substr(p0, p1 - p0);
				tokens.push_back(token);
			}
			p0 = str.find_first_not_of(delim, p1);
		}
		
		return tokens;
	}

}